package com.uzai.console.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkim_1_0.models.BatchQueryGroupMemberHeaders;
import com.aliyun.dingtalkim_1_0.models.BatchQueryGroupMemberRequest;
import com.aliyun.dingtalkim_1_0.models.BatchQueryGroupMemberResponse;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.dingtalkservice_group_1_0.models.SendServiceGroupMessageHeaders;
import com.aliyun.dingtalkservice_group_1_0.models.SendServiceGroupMessageRequest;
import com.aliyun.teautil.models.RuntimeOptions;
import com.uzai.common.dto.god.ExclusiveGroupOptDto;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.enums.WorkOrderType;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.dto.dingding.DingExclusiveGroupMessageDto;
import com.uzai.console.entity.DingWarningGroup;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.WorkOrder;
import com.uzai.console.mapper.DingWarningGroupMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class DingExclusiveGroupUtils {


    private static Logger logger = LoggerFactory.getLogger(DingExclusiveGroupUtils.class);
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private com.aliyun.dingtalkoauth2_1_0.Client dingTokenClient;
    @Autowired
    private com.aliyun.dingtalkim_1_0.Client merberMangerClient;
    @Autowired
    private com.aliyun.dingtalkservice_group_1_0.Client dingGroupClient;

    @Autowired
    private DingWarningGroupMapper dingWarningGroupMapper;

    /**
     * 获取accessToken
     *
     * @param appKey
     * @param appSecret
     * @return
     */
    public String getAccessToken(String appKey, String appSecret) {
        String accessToken = null;
        if (StringUtils.isAllBlank(appKey, appSecret)) {
            Object json = redisTemplate.opsForValue().get(RedisCacheKeyEnum.DING_DING_EXCLUSIVE_GROUP.getKey());
            if (ObjectUtils.isEmpty(json)) {
                return null;
            }
            ExclusiveGroupOptDto exclusiveGroupOptDto = JSON.parseObject(json.toString(), ExclusiveGroupOptDto.class);
            if (Objects.isNull(exclusiveGroupOptDto)) {
                return null;
            }
            appKey = exclusiveGroupOptDto.getAppKey();
            appSecret = exclusiveGroupOptDto.getAppSecret();
        }

        try {
            Object o1 = redisTemplate.opsForValue().get(RedisCacheKeyEnum.DING_TALK_OAUTH_ACCESS_TOKEN.getKey());
            if (o1 == null) {
                GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                        .setAppKey(appKey)
                        .setAppSecret(appSecret);
                GetAccessTokenResponse getAccessTokenResponse = dingTokenClient.getAccessToken(getAccessTokenRequest);
                if (getAccessTokenResponse == null || getAccessTokenResponse.getBody() == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "获取accessToken失败");
                }
                accessToken = getAccessTokenResponse.getBody().getAccessToken();
                redisTemplate.opsForValue().set(RedisCacheKeyEnum.DING_TALK_OAUTH_ACCESS_TOKEN.getKey(), accessToken, 100, TimeUnit.MINUTES);
            } else {
                accessToken = o1.toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return accessToken;
    }


    /**
     * 查询群成员
     */
    public void queryGroupMembers() {
        try {
            BatchQueryGroupMemberHeaders batchQueryGroupMemberHeaders = new BatchQueryGroupMemberHeaders();
            batchQueryGroupMemberHeaders.xAcsDingtalkAccessToken = "a252ae9266b13a5fb903e5102bf37da8";
            BatchQueryGroupMemberRequest batchQueryGroupMemberRequest = new BatchQueryGroupMemberRequest()
                    .setOpenConversationId("cidyWhHAzkEYUlWNszUPH24zQ==")
                    .setMaxResults(200L)
                    .setNextToken("0");
            BatchQueryGroupMemberResponse batchQueryGroupMemberResponse = merberMangerClient.batchQueryGroupMemberWithOptions(batchQueryGroupMemberRequest, batchQueryGroupMemberHeaders, new RuntimeOptions());
            System.out.println(batchQueryGroupMemberResponse);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 服务群发送消息
     *
     * @param dingExclusiveGroupMessageDto
     */

    public void sendingExclusiveGroupMessages(DingExclusiveGroupMessageDto dingExclusiveGroupMessageDto) {
        try {
            SendServiceGroupMessageHeaders sendServiceGroupMessageHeaders = new SendServiceGroupMessageHeaders();
            sendServiceGroupMessageHeaders.xAcsDingtalkAccessToken = dingExclusiveGroupMessageDto.getAccessToken();
            SendServiceGroupMessageRequest.SendServiceGroupMessageRequestBtns btns0 = new SendServiceGroupMessageRequest.SendServiceGroupMessageRequestBtns()
                    .setActionURL("http://www.dingtalk.com")
                    .setTitle(dingExclusiveGroupMessageDto.getTitle());
            SendServiceGroupMessageRequest sendServiceGroupMessageRequest = new SendServiceGroupMessageRequest()
                    .setTargetOpenConversationId(dingExclusiveGroupMessageDto.getTargetOpenConversationId())
                    .setTitle(dingExclusiveGroupMessageDto.getTitle())
                    .setContent(dingExclusiveGroupMessageDto.getContent())
                    .setAtMobiles(dingExclusiveGroupMessageDto.getAtMobiles())
                    .setAtDingtalkIds(dingExclusiveGroupMessageDto.getAtDingtalkIds())
                    .setAtUnionIds(dingExclusiveGroupMessageDto.getAtUnionIds())
                    .setReceiverMobiles(dingExclusiveGroupMessageDto.getReceiverMobiles())
                    .setReceiverDingtalkIds(dingExclusiveGroupMessageDto.getReceiverDingtalkIds())
                    .setReceiverUnionIds(dingExclusiveGroupMessageDto.getReceiverUnionIds())
                    .setMessageType(dingExclusiveGroupMessageDto.getMessageType())
                    .setBtnOrientation(dingExclusiveGroupMessageDto.getBtnOrientation())
                    .setBtns(java.util.Arrays.asList(btns0))
                    .setIsAtAll(dingExclusiveGroupMessageDto.getAtAll());
            dingGroupClient.sendServiceGroupMessageWithOptions(sendServiceGroupMessageRequest, sendServiceGroupMessageHeaders, new RuntimeOptions());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 钉钉报警群发送消息
     * @param id
     * @param content
     */

    public void dingWarningGroupTips(Long id,String content) {
        DingWarningGroup dingWarningGroup = dingWarningGroupMapper.queryDingWarningGroupById(id);
        if (Objects.isNull(dingWarningGroup)) {
            logger.warn("钉钉群配置未找到");
            return;
        }
        JSONObject configJson = JSON.parseObject(dingWarningGroup.getGroupConfig());
        if (Objects.isNull(configJson)) {
            logger.warn("钉钉群配置解析为空");
            return;
        }
        String openConversationId = configJson.getString("openConversationId");
        if (StringUtils.isBlank(openConversationId)) {
            logger.warn("钉钉群配置群id为空");
            return;
        }

        String accessToken = getAccessToken("dinggbqnqmkldsz7xr4f", "ENXv0vO7a5JZR1YKtp1jOhO3TkvVseTE62xOEbXb5ktwha9YSvsryD1PpwvE_ldc");
        if (StringUtils.isBlank(accessToken)) {
            logger.warn("钉钉群AccessToken获取失败, 结果为空");
            return;
        }

        DingExclusiveGroupMessageDto dingExclusiveGroupMessageDto = new DingExclusiveGroupMessageDto();
        dingExclusiveGroupMessageDto.setAccessToken(accessToken);
        dingExclusiveGroupMessageDto.setTargetOpenConversationId(openConversationId);
        dingExclusiveGroupMessageDto.setTitle("异常报警通知");
        dingExclusiveGroupMessageDto.setMessageType("MARKDOWN");
        if(dingWarningGroup.getTipAllMember()==1){
            dingExclusiveGroupMessageDto.setAtAll(true);
        }
        dingExclusiveGroupMessageDto.setContent(content);
        sendingExclusiveGroupMessages(dingExclusiveGroupMessageDto);
    }
}
